import axios from 'axios'
import router from '../router'
import { getStore, clearStore, setStore } from '../utils/storage'
import {isRefreshTokenExpired, getRefreshToken} from '../assets/js/format'
import { Message } from 'element-ui'

const ROOT = process.env.API_URL
window.refresh = false

// 请求时
axios.interceptors.request.use(
  config => {
    let token = getStore('token')
    if (token) {
      config.headers.Authorization = 'Bearer.' + token
    } else {
      router.push({ path: '/login' }).catch(err => err)
      clearStore()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 请求完成
axios.interceptors.response.use(
  response => {
    let expiredIn = getStore('expiredIn')
    let token = getStore('token')
    if (token) {
      isRefreshTokenExpired(expiredIn)
      if (expiredIn < 720) { // token 过期时间剩余6个小时时，一旦有请求就重新刷新 token
        if (!window.refresh) {
          window.refresh = true
          let refreshToken = getStore('refreshToken')
          getRefreshToken(refreshToken).then(res => {
            window.refresh = false
            isRefreshTokenExpired(res.expiredIn)
            setStore('token', res.accessToken)
            setStore('refreshToken', res.refreshToken)
          }).catch(err => {
            return Promise.reject(err.response)
          })
        }
      } else window.refresh = false
    }

    return response
  },
  error => {
    return Promise.reject(error.response)
  }
)

function successState (res) {
  // 判断后台返回错误码
  if (
    res.data.code === 406 ||
    res.data.code === 401 ||
    res.data.code === 405 ||
    res.data.code === 700 ||
    res.data.code === 400
  ) {
    Message.warning(res.data.message, 2)
    router.push({ path: '/login' }).catch(err => err)
    clearStore()
  }

  if (
    res.data.code === 600 ||
    res.data.code === 601 ||
    res.data.code === 602 ||
    res.data.code === 500
  ) {
    Message.warning(res.data.message, 2)
  }
}

function errorState (err) {
  // 状态码为200，直接返回数据
  if (err.status === 400 || err.status === 401) {
    router.push({ path: '/login' }).catch(err => err)
  } else if (err && (err.status === 200 || err.status === 304)) {
    return err
  } else if (err.status === 504) {
    Message.warning(err.statusText, 2)
  } else {
    Message.warning(err.message, 2)
  }
}

const httpServer = (opts, data) => {
  let httpDefaultOpts = {
    method: opts.method,
    url: opts.url,
    timeout: 300000,
    baseURL: ROOT,
    // get
    params: data,
    data: data,
    headers: opts.method === 'get' ? {
      'X-Requested-With': 'XMLHttpRequest',
      'Accept': 'application/json',
      'Content-Type': 'application/json;charset=UTF-8'
    } : {
      'X-Requested-With': 'XMLHttpRequest',
      'Content-Type': 'application/json;charset=UTF-8'
    }
  }

  if (opts.method === 'get') {
    delete httpDefaultOpts.data
  } else {
    delete httpDefaultOpts.params
  }

  return new Promise((resolve, reject) => {
    axios(httpDefaultOpts)
      .then(res => {
        successState(res)
        resolve(res.data)
      })
      .catch(err => {
        errorState(err)
        reject(err)
      })
  })
}

export default httpServer
